const request = require('request');
const fs = require('fs');

Date.prototype.format = function(fmt)   
{ //author: meizz   
  var o = {   
    "M+" : this.getMonth()+1,                 //月份   
    "d+" : this.getDate(),                    //日   
    "h+" : this.getHours(),                   //小时   
    "m+" : this.getMinutes(),                 //分   
    "s+" : this.getSeconds(),                 //秒   
    "q+" : Math.floor((this.getMonth()+3)/3), //季度   
    "S"  : this.getMilliseconds()             //毫秒   
  };   
  if(/(y+)/.test(fmt))   
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));   
  for(var k in o)   
    if(new RegExp("("+ k +")").test(fmt))   
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));   
  return fmt;   
}

function promiseRequest(json) {

  const options = {
    url: 'http://api.waditu.com',
    method: 'POST',
    json: json
  };

  return new Promise(function (resolve, reject) {
    request(options, function (err, res, body) {
      if (err) {
        return reject(err);
      } else if (res.statusCode !== 200) {
        err = new Error("Unexpected status code: " + res.statusCode);
        err.res = res;
        return reject(err);
      }
      resolve(body);
    });
  });
}


function writeFile(json, filePath) {
  try {
    fs.writeFile(filePath, JSON.stringify(json, null, 4),
      function (err) {
        if (err) {
          console.log(filePath + "文件写入失败")
        } else {
          console.log(filePath + "文件写入成功");
        }
      })
  } catch (e) {
    console.log(e);
  }
}


; (async () => {

  let cal = JSON.parse(fs.readFileSync('trade_cal.json'));
  let basic = JSON.parse(fs.readFileSync('stock_basic.json'));

  if (!fs.existsSync('ups') ) {
    fs.mkdirSync('ups')
  }

  let upindex = []

  // for (let index = 0; index < 10; index++) {
  for (let index = 0; index < cal.length; index++) {
    const daily = cal[index];
    // 开市的日子
    if (daily[1] == 0) {
      console.log('不开市. ', daily[0]);
      continue;
    }
    // 判断文件是否存在
    var filePath = 'dailys/' + daily[0] + '.json'
    if (!fs.existsSync(filePath)) {
      console.log('文件没找到. ', filePath);
      continue;
    }
    // 到今天就不找了
    var time2 = new Date().format("yyyyMMdd");  

    if (daily[0] == time2) {
      console.log(time2 + ' end');
      break;
    }

    console.log(daily);

    let dailys = JSON.parse(fs.readFileSync(filePath));

    let ups = []
    // 循环每只股票，看看那个涨停，并判断是否连板
    dailys.forEach(element => {
      // 看看那个涨停
      if (element[2] > 9.68 && element[2] < 10.3) {

        let name = basic.find(function (e) {
          return e[0] == element[0]
        })
        if (name) {
          element.unshift(name[2])
        } else {
          element.unshift('没找到啊')
        }

        ups.push(element)

        // 判断是否连板
        if (upindex.length > 0) {
          const upsx = upindex[upindex.length - 1]['list'];
          let findx = upsx.find(function (e) {
            return e[1] == element[1]
          })
          if (findx) {
            element.push(findx[5] + 1)
          } else {
            element.push(1)
          }
        } else {
          element.push(1)
        }
      }
    });

    ups = ups.sort(function (e1, e2) {
      return e2[5] - e1[5]
    })
    let total = {}
    ups.forEach((e) => {
      total[e[5]] = total[e[5]] ? total[e[5]] + 1 : 1;
    })
    let totalStr = ''
    // total.forEach((k,e)=>{
    //    totalStr = totalStr + '/' + k + '连:' + e + '只'
    // })
    let maxStr = 0;
    for (var k in total) {
      maxStr = k;
      totalStr =  '/' + k + '连板' + total[k] + '只' + totalStr 
    }

    totalStr = totalStr + '/涨停共' + ups.length + '只/'
    // final['total'] = ups.length
    let final = {}
    final['total'] = totalStr
    final['max'] = maxStr
    final['date'] = daily[0]
    final['list'] = ups
    // ups.unshift(total)
    upindex.push(final)

  }

  let xxx = []
  let fisrt = upindex.length > 50 ? upindex.length - 50: 0;
  for (let xx = fisrt;xx < upindex.length; xx ++) {
    const element = upindex[xx];
    const new1 = element['list'].map((item)=>{
      if (item[5] < 3) {
        return {};
      }else{
        return {
          name: item[0],
          code: item[1],
          close: item[2],
          up: item[3],
          vol: item[4],
          last: item[5]
        }
      }
    })
    element['list'] = new1
    xxx.push(element)
  }

  // console.dir(upindex);

  writeFile(xxx, 'ups/total.json')


})()